package com.ruoyi.web.controller;

import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.domain.Post;
import com.ruoyi.web.service.FileService;
import com.ruoyi.web.service.IImageService;
import com.ruoyi.web.service.IPostService;
import com.ruoyi.web.utils.UserMsgUtil;
import io.swagger.annotations.ApiOperation;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 * postController
 *
 * @author ruoyi
 * @date 2024-04-22
 */
@RestController
@RequestMapping("/wx/post")
public class PostController extends BaseController {
    @Autowired
    private IPostService postService;
    @Autowired
    private IImageService imageService;
    @Autowired
    private FileService fileService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取usreId
     * @return
     */
    @GetMapping("/getUserId")
    public AjaxResult getUser() {
        Long userId = UserMsgUtil.getUserId();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("userId",userId);
        return AjaxResult.success(map);
    }

    /**
     * 查询post列表(查询所有和查询自己的)
     */
    @GetMapping("/listOri")
    public TableDataInfo listOri(Post post) {
        startPage();
        List<Post> list = postService.selectPostListOri(post);
        return getDataTable(list);
    }

    /**
     * 查询post列表(查询所有和查询自己的)
     */
    @GetMapping("/list")
    public AjaxResult list(Post post, Boolean myFlag) {
//        startPage();
        List<Post> list = postService.selectPostList(post, myFlag);
//        return getDataTable(list);
        return AjaxResult.success(list);
    }

    /**
     * 导出post列表
     */
    @Log(title = "post", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Post post) {
        List<Post> list = postService.selectPostList(post, false);
        ExcelUtil<Post> util = new ExcelUtil<Post>(Post.class);
        util.exportExcel(response, list, "post数据");
    }

    /**
     * 获取post详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        // 查询该post下的内容、评论、头像url
        return success(postService.selectPostById(id));
    }

    /**
     * 新增post
     */
    @Log(title = "post", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Post post) throws MalformedURLException {
//        System.err.println(post);
        // 存post到数据库中
        int rows = postService.insertPost(post);
        if (!post.getTempFilePathList().isEmpty()) {
            //将传来的图片路径存image中，格式： src/post/test.jpg
            List<String> imgList = post.getTempFilePathList();
            // 拆解
            imgList = getOriginName(imgList);
            // 存入image数据库
            if (rows > 0) {
                // post插入成功
                // toAjax自己封装了对于增、改的rows的判断
                return toAjax(imageService.batchInsertImages(imgList, post));
            }
            // post插入失败
            return AjaxResult.error();
        }
        return toAjax(rows);
    }

    private List<String> getOriginName(List<String> tempFilePathList) {
        // 手动拆解格式成：src/post/test.jpg
        tempFilePathList = tempFilePathList.stream().map(item -> {
            // src/post/test.jpg
            String filename = item.substring(item.lastIndexOf("/") + 1);
            return "src/post/" + filename;
        }).collect(Collectors.toList());
        return tempFilePathList;
    }

    @NotNull
    private String getOriginName(String url) {
        // 查找最后一个"/"的位置
        int lastSlashIndex = url.lastIndexOf("/");
        // 查找第一个"?"的位置
        int firstQuestionMarkIndex = url.indexOf("?");
        // 确保"/"在"?"之前，并根据位置截取字符串
        String fileName = url.substring(lastSlashIndex + 1, firstQuestionMarkIndex);
        return fileName;
    }

    /**
     * 修改post
     */
    @Log(title = "post", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Post post) {
        return toAjax(postService.updatePost(post));
    }

    /**
     * 删除post
     */
    @Log(title = "post", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(postService.deletePostByIds(ids));
    }

    /**
     * 帖子图片上传oss
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public AjaxResult upload(@RequestPart("file") MultipartFile file) throws Exception {
//        System.err.println(file.getOriginalFilename());
        String uploadFlag = fileService.upload(file, "src/post/" + file.getOriginalFilename());
        if (uploadFlag == "上传成功") {
            return AjaxResult.success("上传成功");
        } else {
            return AjaxResult.error("上传失败");
        }
    }

}
